package org.zbclan.bf2.rcon.ui;

import java.util.Collection;
import java.util.Set;

import org.apache.commons.lang.StringUtils;
import org.zbclan.bf2.rcon.BF2RconAppRunner;
import org.zbclan.bf2.rcon.event.RunAppletEvent;
import org.zbclan.bf2.rcon.model.LocalProfile;

import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Table;
import com.vaadin.ui.VerticalLayout;

public class LocalProfileSelectComponent extends VerticalLayout implements
		Button.ClickListener {

	/**
	 * 
	 */
	private static final long serialVersionUID = -8822555671380779826L;

	private final BF2RconAppRunner appRunner;

	private final Table table;
	private final Button uploadButton;

	public LocalProfileSelectComponent(BF2RconAppRunner appRunner) {

		this.appRunner = appRunner;

		table = new Table();
		// table.addContainerProperty("name", String.class, null);
		// table.addContainerProperty("nick", String.class, null);
		table.addContainerProperty("gamespyNick", String.class, null);
		table.addContainerProperty("email", String.class, null);
		// table.addContainerProperty("password", String.class, null);
		table.addContainerProperty("totalPlayedTime", Float.class, null);
		table.addContainerProperty("numTimesLoggedIn", Integer.class, null);
		table.setColumnHeaders(new String[] { "Nickname", "Email",
				"Total Played Time", "Login Count" });
		table.setSelectable(true);
		table.setMultiSelect(true);

		uploadButton = new Button("upload", (Button.ClickListener) this);

		addComponent(table);
		addComponent(uploadButton);
		setComponentAlignment(uploadButton, Alignment.MIDDLE_CENTER);

		return;
	}

	public void display(Collection<LocalProfile> profiles) {

		table.removeAllItems();

		for (LocalProfile p : profiles) {
			table.addItem(
					new Object[] { p.getGamespyNick(), p.getEmail(),
							p.getTotalPlayedTime(), p.getNumTimesLoggedIn() },
					p);
		}

		return;
	}

	@Override
	public void buttonClick(ClickEvent event) {

		Button button = event.getButton();
		if (button == uploadButton) {
			/*
			 * upload
			 */
			@SuppressWarnings("unchecked")
			Set<LocalProfile> profiles = (Set<LocalProfile>) table.getValue();
			String[] dir = new String[profiles.size()];
			int i = 0;
			for (LocalProfile p : profiles) {
				dir[i] = p.getPlatformDir();
				i++;
			}
			appRunner.fireEvent(new RunAppletEvent("cmd=uploadLocalProfiles",
					"dir=" + StringUtils.join(dir, ",")));
		}

		return;
	}
}
